package j_util.sorters;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Comparator;
import java.util.List;

public abstract class Sort {
    protected int moves;
    protected int comparisons;
    protected long time;

    public <T> boolean less(T u, T w, Comparator<T> c) {
        comparisons++;
        return c.compare(u, w) < 0;
    }

    public <T> void exchange(List<T> list, int i, int j) {
        moves++;
        T temp = list.get(i);
        list.set(i, list.get(j));
        list.set(j, temp);
    }

    public <T> boolean compareAndExchange(List<T> list, int left, int right, Comparator<T> comparator) {
        comparisons++;
        if (less(list.get(right), list.get(left), comparator)) {
            exchange(list, left, right);
            moves++;
            return true;
        }
        return false;
    }

    public abstract <T> void sort(List<T> list, int left, int right, Comparator<T> c);

    public <T> boolean equal(T u, T w, Comparator<T> c) {
        comparisons++;
        return (!less(u, w, c) && !less(w, u, c));
    }

    public int min(int a, int b) {
        if (a < b) {
            return a;
        }
        return b;
    }

    public void resetVariables() {
        time = 0;
        comparisons = 0;
        moves = 0;
    }

    public int comparisons() {
        return comparisons;
    }

    public long runningTime() {
        return time;
    }

    public int moves() {
        return moves;
    }

    public void exportResults(String sortName, int proofSize, char modus) {
        try {
            File file = new File("Exported Data " + sortName + " " + modus + "" + proofSize + ".txt");
            file.delete();
            RandomAccessFile exportedData = new RandomAccessFile("Exported Data " + sortName + " " + proofSize + modus + ".txt", "rw");
            String columns = "n\tTime\tComparisons\tMoves\n";
            System.out.println("" + columns);
            try {
                exportedData.writeUTF(columns);
            } catch (IOException e) {
                e.printStackTrace();
            }
            columns = "" + proofSize + "\t" + time + "\t"
                    + comparisons + "\t" + moves + "\t" + "\n";
            System.out.println("" + columns);
            try {
                exportedData.writeUTF(columns);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        }
    }
}
